<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="title" :visible="showDialog" @close="btnCancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @blur="checkManager">
          <el-option v-for="user in Employe" :key="user.id" :label="user.username" :value="user.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { department, addDepartments, editDepartment } from '@/api/department.js'
import { getEmployeeSimple } from '@/api/employees.js'
export default {

  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    node: {
      type: Object,
      required: true
    }
  },
  data: function() {
    // 自定义检验
    const validateName = (rule, val, callback) => {
      if (val.length > 50) {
        callback(new Error('部门编码要求1-50个字符'))
      }
      if (this.formData.id) {
        this.depts.forEach((ele) => {
          // 如果是编辑状态，则同名条件需要满足同级部门不同名
          if (ele.pid === this.formData.pid && ele.name === val && ele.id !== this.formData.id) {
            callback(new Error('已经有同名的部门'))
          }
        })
      } else {
        this.depts.forEach((ele) => {
          if (ele.pid === this.node.id && ele.name === val) {
            callback(new Error('已经有同名的部门'))
          }
        })
      }
      callback()
    }
    const validateCode = (rule, val, callback) => {
      let isRepeat
      if (this.formData.id) {
        isRepeat = this.depts.some((item) => item.code === val && item.id !== this.formData.id)
      } else {
        isRepeat = this.depts.some((item) => {
          return item.code === val
        })
      }
      isRepeat ? callback(new Error('已经有同名的编号')) : callback()
    }
    return {
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      Employe: [],
      depts: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空' },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空' },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [{ required: true, message: '部门负责人不能为空' }],
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-300个字符' }]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  async created() {
    this.getdepartment()
    // // console.log(depts)
    // 获取用户列表
    this.Employe = await getEmployeeSimple()
  },
  methods: {
    async getdepartment() {
      // 查询企业的部门列表
      const { depts } = await department()
      this.depts = depts
    },
    // 修改列表
    list() {
      this.depts = this.depts.map((ele) => {
        if (ele.id === this.formData.id) {
          ele = this.formData
        }
        return ele
      })
    },
    checkManager() {
      this.$refs.addDept.validateField('manager')
    },
    async btnOK() {
      // 对整个表单进行验证
      try {
        await this.$refs['addDept'].validate()
        if (this.formData.id) {
          await editDepartment({
            ...this.formData,
            pid: this.node.id
          })
        } else {
          await addDepartments({
            ...this.formData,
            pid: this.node.id
          })
        }
        this.list()
        this.$message.success('操作成功')
        this.$emit('update:showDialog', false)
        this.$emit('addDepartment')
      } catch (err) {
        console.log(err)
      }
    },
    eidtdepartment(node) {
      this.formData = node
    },
    btnCancel() {
      this.formData = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
      this.$refs.addDept.resetFields()
      this.$emit('update:showDialog', false)
    }

  }
}
</script>

<style>

</style>
